package cn.wsn2018.tools.util;

import org.apache.log4j.Logger;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用于存放内部存储信息的类
 */
public class StorageUtil {
    private Logger logger = Logger.getLogger(ServletUtil.class);
    private static StorageUtil instance=null;

    //用于存放在线用户的SessionID的映射表
    //StorageUtil.getInstance().setLoginSessions(username,session.getId());
    private static Map<String, String> loginSessions = new ConcurrentHashMap<>();
    //用于存放已经包含的时间戳
    private static Set<String> timeSets=new HashSet<>();

    private StorageUtil(){}

    /**
     * 得到单例的接口，确保只有一个实例
     * @return
     */
    public static StorageUtil getInstance(){
        if(instance==null){
            synchronized(ServletUtil.class){
                if(instance==null)
                    instance=new StorageUtil();
            }
        }
        return instance;
    }


    public  Map<String, String> getLoginSessions() {
        return loginSessions;
    }

    public  void setLoginSessions(String username,String sessionId) {
        if(!loginSessions.containsKey(username))
            loginSessions.put(username,sessionId);
    }

    /**
     * 向内存中存放时间戳
     * @param TimeLine
     */
    public void setTimeLine(String TimeLine){
        if(!timeSets.contains(TimeLine))
            timeSets.add(TimeLine);
    }

    /**
     * 判断内存中是否已经包含该时间戳
     * @param TimeLine
     * @return
     */
    public boolean containsTimeLine(String TimeLine){
        return  timeSets.contains(TimeLine);
    }

    /**
     * 用于session销毁时移除sessionId
     * @param sessionId
     */
    public  void removeSessions(String sessionId) {
        for (Map.Entry<String, String> entry : loginSessions.entrySet()) {
            if (sessionId.equals(entry.getValue())) {
                loginSessions.remove(entry.getKey());
                break;
            }
        }
    }

    /**
     * 根据用户名删除列表里的在线用户
     * @param username
     */
    public void removeUser(String username){
        if(loginSessions.containsKey(username)){
            loginSessions.remove(username);
        }
    }

    /**
     * 判断是否在loginSessions中
     * @param username
     * @param sessionId
     * @return
     */
    public static boolean isInLoginSessions(String username, String sessionId) {
        return (loginSessions.containsKey(username) && sessionId.equals(loginSessions.get(username)));
    }


    /**
     * 根据id查name
     * @param sessionId
     * @return
     */
    public String getNameById(String sessionId){
        return getKey(loginSessions,sessionId);
    }


    public <K, V> K getKey(Map<K, V> map, V value) {
        for (Map.Entry<K, V> entry : map.entrySet()) {
            if (entry.getValue().equals(value)) {
                return entry.getKey();
            }
        }
        return null;
    }

}